package com.aacar.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aacar.dao.ThirdCommonDao;
import com.aacar.entity.WashCityDto;
import com.aacar.service.ThirdCommonService;
import com.aacar.utils.HttpUtil;
import com.aacar.vo.WashIndexVo;

@Repository("thirdCommonService")
public class ThirdCommonServiceImpl implements ThirdCommonService {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ThirdCommonDao thirdCommonDao;
	
	@Override
	public WashIndexVo getWashResultVo(WashCityDto washCityDto) {
		//https://www.sojson.com/open/api/weather/json.shtml
		String url = "https://www.sojson.com/open/api/weather/xml.shtml?city=%s";
		String index;
		WashIndexVo result = this.thirdCommonDao.selectWealthIndex();
		if(null != result) {
			return result;
		}
		WashIndexVo wiv = new WashIndexVo();
		//先查询数据库
		try {
			index = HttpUtil.getWealthjson(url, washCityDto.getCityName());
			int length = index.length();
			logger.info("wealth index == "+length+"===,result="+index);
			if(length == 0) {
				return null;
			}
			String washIndex = index.substring(index.indexOf("<zhishu>"),length);
			washIndex = washIndex.substring(washIndex.indexOf("洗车指数"),washIndex.length());
			String washIndex1 = washIndex.substring(washIndex.indexOf("<value>")+7,washIndex.indexOf("</value>"));//洗车指数;
			String washIndexDetail = washIndex.substring(washIndex.indexOf("<detail>")+8,washIndex.indexOf("</detail>"));//洗车指数详情;
			//获取当前温度
			String currentTemperature = index.substring(index.indexOf("<wendu>")+7, index.indexOf("</wendu>"));//当前温度
			String highTemperature = index.substring(index.indexOf("<high>")+6, index.indexOf("</high>"));//最高温度
			String lowTemperature = index.substring(index.indexOf("<low>")+5, index.indexOf("</low>"));//最低温度
		    String wealth = index.substring(index.indexOf("<type>")+6, index.indexOf("</type>"));//天气状况
		    wiv.setCurrentTemperature(currentTemperature);//当前温度
		    wiv.setHigh(trimStr(highTemperature));//最高温度
		    wiv.setLow(trimStr(lowTemperature));//最低温度
		    wiv.setWashDetail(washIndexDetail);//是否适合洗车详情
		    wiv.setWashIndex(washIndex1);//是否适合洗车
		    wiv.setWealth(wealth);
		    this.thirdCommonDao.saveWealthIndex(wiv);//插入数据库表
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return wiv;
	}
	
	//截取字符串
	private String trimStr(String str) {
		str = str.trim();
		String str2 = "";
		if (str != null && !"".equals(str)) {
			for (int i = 0; i < str.length(); i++) {
				if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
					str2 += str.charAt(i);
				}
			}
		}
		return str2;
	}
	
}
